<?php
namespace app\work\controller;
use \think\Db;
class Index extends Base
{
    /**
     * 首页展示未开发和已开发的
     * @return string
     */
    public function index()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
//        $lat = '31.969928741455078';
//        $lon = '118.7648696899414';
        $where = array();
        $where['s_status'] = 1;//不能是信用太低的
        $mile = Db::table('up_set_juli')->where('juli_id',3)->value('juli_value');
        $miles = (int)$mile*1000;
        $field = 's_id,s_pinlei_id';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $yess1 = Db::table('up_shops')
            ->field($field)
            ->where($where)
//            ->group('s_pinlei_id')
            ->having("distance <= $miles")
            ->select();
        $yess2 = array();
        $number = Db::table('up_work_order')
            ->where('o_agree',1)
            ->where('o_status',2)
            ->column('o_number');
        if($number){
            $where2 = array();
            $where2['s_ordernumber'] = array('in',$number);
            $yess2 = Db::table('up_work_shops_copy')
                ->field($field)
                ->where($where2)
//                ->group('s_pinlei_id')
                ->having("distance <= $miles")
                ->select();

        }
        $yess = array_merge($yess1,$yess2);
        $yesdata = array();
        if($yess){
            $yes = array();
            foreach ($yess as $k=>$v){
                $yes[] = $v['s_pinlei_id'];
            }
            $yesdata = Db::table('up_work_pl')
                ->where('pl_id','in',$yes)
                ->select();
            $nodata = Db::table('up_work_pl')
                ->where('pl_id','not in',$yes)
                ->select();
        }else{
            $nodata = Db::table('up_work_pl')->select();
        }
        return json_encode(['status'=>200,'yesdata'=>$yesdata,'nodata'=>$nodata]);
    }
    /**
     * 开发商户
     * @return string
     */
    public function newShopNext()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $shop = Db::table('up_shops')
            ->where('s_phone',$phone)
            ->find();
        $shop2 = Db::table('up_shops')
            ->where('s_bianhao',$bianhao)
            ->find();
        //----------------重复提交--------------
        $re = newShopRepeatRight($phone,$bianhao);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------重复提交end-------------
        //----------------验证码--------------
        $re = newShopPhonecodeRight($phone,$code);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------验证码end-------------
        if($shop){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码商户了']);
        }else if($shop2){
            return json_encode(['status'=>0,'msg'=>'已经有此营业执照编号了']);
        }else{
            return json_encode(['status'=>200,'msg'=>'ok']);
        }
    }
    public function newShop()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $shop = Db::table('up_shops')->where('s_phone',$phone)->find();
        if(!empty($shop)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码商户了']);
        }
        //----------------重复提交--------------
        $re = newShopRepeatRight($phone,$bianhao);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------重复提交end-------------
        Db::startTrans();
        try{
            $number = date('YmdHis') . rand(1000000, 9999999);
            $plname = Db::table('up_work_pl')->where('pl_id',$pinlei_id)->value('pl_name');
            $data = array();
            $data['s_name'] = $name;
            $data['s_pinlei_id'] = $pinlei_id;
            $data['s_pinlei'] = $plname;
            $data['s_bianhao'] = $bianhao;
            $data['s_phone'] = $phone;
            $data['s_beiyongphone'] = $two_phone;
            $data['s_address'] = $address;
            $data['s_lat'] = $lat;
            $data['s_lon'] = $lon;
            $data['s_image'] = trim($image,',');
            $data['s_door'] = trim($door,',');
            $data['s_inside'] = trim($inside,',');
            //------------
            $data['s_zheng'] = trim($zheng,',');
            $data['s_fan'] = trim($fan,',');
            $data['s_shou'] = trim($shou,',');
            if(isset($food)){
                $data['s_food'] = trim($food,',');
            }
            //------------
            $data['s_ordernumber'] = $number;
            $data['s_work_user_id'] = $user_id;
            $data['s_join_in'] = date('Y-m-d');
            $data['s_join_end'] = date("Y-m-d",strtotime("+1 year"));
            Db::table('up_work_shops_copy')->insert($data);
            //算钱
            $regdate = Db::table('up_work_user')->where('user_id',$user_id)->value('user_date');
            $allprice = Db::table('up_set_juli')->where('juli_id',4)->value('juli_value');
            $mytc = Db::table('up_set_juli')->where('juli_id',5)->value('juli_value');
            $low = Db::table('up_set_juli')->where('juli_id',8)->value('juli_value');
            $high = Db::table('up_set_juli')->where('juli_id',9)->value('juli_value');
            $step = Db::table('up_set_juli')->where('juli_id',10)->value('juli_value');
            //上次成交时间
            $lastdata = Db::table('up_work_order')
                ->where('o_user_id',$user_id)
                ->where('o_status',2)
                ->where('o_level',1)
                ->order('o_datetime DESC')
                ->field('o_date,o_money')
                ->find();
            if($lastdata){//如果有成交记录
                $days = $this->diffBetweenTwoDays($lastdata['o_date']);//有几天没成交了
                $lastmoney = $lastdata['o_money'];//上次成交价格
                if($days <= 1){//如果差不到两天
                    $money = $lastmoney+$step;//加步进值
                }else{//如果超过两天
                    $money = $lastmoney-(($days-1)*$step);//减步进值（减一先）
                }
            }else{//如果没有成交记录
                $days = $this->diffBetweenTwoDays($regdate);//有几天没成交了
                $lastmoney = $mytc;//上次成交价格（即默认初始价格）
                if($days <= 0){//如果差不到两天
                    $money = $lastmoney;//加步进值
                }else{//如果超过两天
                    $money = $lastmoney-($days*$step);//减步进值
                }
            }

            //计算
            if($money < $low){//超出最低
                $money = $low;
            }
            if($money > $high){//超出最高
                $money = $high;
            }
            //---
            $order = array();//TODO
            $order['o_number'] = $number;
            $order['o_user_id'] = $user_id;
            $order['o_level'] = 1;
            $order['o_money'] = round($money,2);
            $order['o_type'] = $type;
            $order['o_user_pay'] = $allprice;
            $order['o_date'] = date('Y-m-d');
            $order['o_datetime'] = date('Y-m-d H:i:s');
            Db::table('up_work_order')->insert($order);
            Db::commit();
            //改验证码状态
            Db::table('up_shop_phonecode')->where('phone',$phone)->update(['status'=>1]);
            if($type == 1){
                $respont = $this->getParam($number,'0.01');
                if($respont['status'] == 200){
                    $decodeurl=urldecode($respont['msg']);
                    $a = qrcode($decodeurl);
                    return json_encode(['status'=>200,'msgsss'=>$a,'order_num'=>$number]);
                }else{
                    return json_encode(['status'=>0,'msg'=>$respont['msg']]);
                }
            }else{
                $orderWx = array();
                $orderWx['body'] = '红集';
                $orderWx['total_fee'] = 1;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'NATIVE';
                $respont = $this->WeChatPayReady($orderWx);
                $decodeurl=urldecode($respont['code_url']);
                $a = qrcode($decodeurl);
                return json_encode(['status'=>200,'msgsss'=>$a,'order_num'=>$number]);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'保存失败1234567']);
        }
    }

    /**
     * 传订单号：number
     * 查询支付状态
     * @return string
     */
    public function payGetStatus()
    {
        extract(input());
        $status = Db::table('up_work_order')
            ->where('o_number', $number)
            ->value('o_status');
        if($status == 2){
            return json_encode(['status'=>200]);
        }else{
            return json_encode(['status'=>0]);
        }

    }

    /**
     * 开发商户
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if ($getInfo) {
            if ($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try {
                    $number = $getInfo['out_trade_no'];
                    $transaction_id = $getInfo['trade_no'];
                    //2、修改订单状态
                    $update = array();
                    $update['o_status'] = 2;
                    $update['o_transaction_id'] = $transaction_id;
                    Db::table('up_work_order')
                        ->where('o_number', $number)
                        ->update($update);
                    //通知
                    $shopname = Db::table('up_work_shops_copy')
                        ->where('s_ordernumber', $number)
                        ->value('s_name');
                    $userid = Db::table('up_work_order')
                        ->where('o_number', $number)
                        ->value('o_user_id');
                    allInNotice('商户审核','你提交的:'.$shopname.',商户资料正在认证，认证成功后会立刻适配商城，请耐心等待。',$userid);
                    Db::commit();
                    die('success');
                } catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
    public function huidiaoWx()
    {
        $xml=file_get_contents('php://input', 'r');
        $getInfo=$this->toArray($xml);
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign = $this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            $number = $getInfo['out_trade_no'];
            $transaction_id = $getInfo['transaction_id'];
            $update = array();
            $update['o_status'] = 2;
            $update['o_transaction_id'] = $transaction_id;
            $res = Db::table('up_work_order')
                ->where('o_number', $number)
                ->update($update);
            //通知
            $shopname = Db::table('up_work_shops_copy')
                ->where('s_ordernumber', $number)
                ->value('s_name');
            $userid = Db::table('up_work_order')
                ->where('o_number', $number)
                ->value('o_user_id');
            allInNotice('商户审核','你提交的:'.$shopname.',商户资料正在认证，认证成功后会立刻适配商城，请耐心等待。',$userid);
            if ($res) {
                $result = $getInfo;
            } else {
                $result = false;
            }
        }else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }

    /**
     * 同意开发商户：后台调用
     * @return string
     */
    public function agreeShopIn($o_id,$adminname)
    {
        $o = Db::table('up_work_order')
            ->where('o_id', $o_id)
            ->field('o_agree,o_number')
            ->find();
        $o_agree = $o['o_agree'];
        if($o_agree == 2){
            return array('status'=>101,'msg'=>'已经同意过了');
        }
        if($o_agree == 3){
            return array('status'=>100,'msg'=>'已经被拒绝了');
        }
        $number = $o['o_number'];
        Db::startTrans();
        try {
            //1-1、获取商铺信息并新建
            $shop = Db::table('up_work_shops_copy')
                ->where('s_ordernumber', $number)
                ->find();
            unset($shop['s_id']);
            $shop['s_id'] = $this->uuid();
            $shop['s_time'] = date('Y-m-d H:i:s');
            $shop['s_clicktime'] = date('Y-m-d H:i:s');
            $shop['s_password'] = md5(substr($shop['s_phone'], 5, 6));
            Db::table('up_shops')->insert($shop);
            //1-2、新建后获得100积分的原因
            //2、修改订单状态
            $update = array();
            $update['o_agree'] = 2;
            $update['o_admin'] = $adminname;
            $update['o_agree_time'] = date('Y-m-d H:i:s');
            Db::table('up_work_order')
                ->where('o_number', $number)
                ->update($update);
            //3、修改我的余额和入消息表(自己就不入了吧)
            $orderdata = Db::table('up_work_order')
                ->where('o_number', $number)
                ->find();
            if($orderdata['o_which'] == 2){
                $jia = Db::table('up_set_juli')->where('juli_id',11)->value('juli_value');
                $shopid = $orderdata['o_user_id'];
                $date = Db::table('up_shops')
                    ->where('s_id', $shopid)
                    ->value('s_join_end');
                $today = date('Y-m-d');
                if($date >= $today){
                    $newDate = date("Y-m-d",strtotime("$date +$jia month"));
                }else{
                    $newDate = date("Y-m-d",strtotime("+$jia month"));
                }
                Db::table('up_shops')->where('s_id', $shopid)->update(['s_join_end'=>$newDate]);
                //----------------入消息表---------------------
                $notice = array();
                $notice['n_title'] = '入驻申请审核通过';
                $notice['n_content'] = '您提交的' . $shop['s_name'] . '商户，资料认证成功，并以适配好商城，您可增加' . $jia . '个月的到期时间,请让商户下载商城后台（红集商家版）app登录，登录账号是你刚刚提交的商户手机号，初始密码是手机号后六位。';
                $notice['n_type'] = 2;
                $notice['n_user_id'] = $shop['s_work_user_id'];
                $notice['n_read'] = 0;
                $notice['n_time'] = date('Y-m-d H:i:s');
                Db::table('up_notice')->insert($notice);
                //--------------------------------------
            }else {
                $ticheng = $orderdata['o_money'];
                Db::table('up_work_user')
                    ->where('user_id', $shop['s_work_user_id'])
                    ->setInc('user_money', $ticheng);
                //----------------入消息表---------------------
                $notice = array();
                $notice['n_title'] = '入驻申请审核通过';
                $notice['n_content'] = '你提交的' . $shop['s_name'] . '，商户资料认证成功，并以适配好商城，你的' . $ticheng . '开户奖励已到账。请让商户下载商城后台（红集商家版）app登录，登录账号是你刚刚提交的商户手机号，初始密码是手机号后六位。';
                $notice['n_type'] = 2;
                $notice['n_user_id'] = $shop['s_work_user_id'];
                $notice['n_read'] = 0;
                $notice['n_time'] = date('Y-m-d H:i:s');
                Db::table('up_notice')->insert($notice);
                //--------------------------------------
                //4-1、上级的提成
                $two = Db::table('up_set_juli')->where('juli_id', 6)->value('juli_value');
                $money2 = round($two, 2);
                //我的上级
                $lead = Db::table('up_work_user')
                    ->where('user_id', $shop['s_work_user_id'])
                    ->field('user_mynum,user_leadnum')
                    ->find();
                $leadnum = $lead['user_leadnum'];
                if ($leadnum) {
                    $leaddata = Db::table('up_work_user')
                        ->where('user_mynum', $leadnum)
                        ->field('user_id,user_money,user_leadnum')
                        ->find();
                    Db::table('up_work_user')
                        ->where('user_mynum', $leadnum)
                        ->setInc('user_money', $money2);
                    //------先入订单表------------
                    $order1 = $orderdata;
                    unset($order1['o_id']);
                    $order1['o_user_id'] = $leaddata['user_id'];
                    $order1['o_status'] = 2;
                    $order1['o_level'] = 2;
                    $order1['o_money'] = $money2;
                    $order1['o_level_user_id'] = $shop['s_work_user_id'];
                    Db::table('up_work_order')->insert($order1);
                    //------------------------------------
                    //-----------------再入消息表---------------------
                    $notice = array();
                    $notice['n_title'] = '我的团队';
                    $notice['n_content'] = '我的一级队员编号' . $lead['user_mynum'] . '开发了新商户，您将可获得' . $money2 . '元提成奖励';
                    $notice['n_type'] = 2;
                    $notice['n_user_id'] = $leaddata['user_id'];
                    $notice['n_read'] = 0;
                    $notice['n_time'] = date('Y-m-d H:i:s');
                    Db::table('up_notice')->insert($notice);
                    //--------------------------------------
                    if ($leaddata['user_leadnum']) {
                        //4-2、上上级的提成
                        $three = Db::table('up_set_juli')->where('juli_id', 7)->value('juli_value');
                        $money3 = round($three, 2);
                        $leaddata2 = Db::table('up_work_user')
                            ->where('user_mynum', $leaddata['user_leadnum'])
                            ->field('user_id,user_money,user_leadnum')
                            ->find();
                        Db::table('up_work_user')
                            ->where('user_mynum', $leaddata['user_leadnum'])
                            ->setInc('user_money', $money3);
                        //------先入订单表------------
                        $order2 = $orderdata;
                        unset($order2['o_id']);
                        $order2['o_user_id'] = $leaddata2['user_id'];
                        $order2['o_status'] = 2;
                        $order2['o_level'] = 3;
                        $order2['o_money'] = $money3;
                        $order2['o_level_user_id'] = $shop['s_work_user_id'];
                        Db::table('up_work_order')->insert($order2);
                        //-----------------再入消息---------------------
                        $notice = array();
                        $notice['n_title'] = '我的团队';
                        $notice['n_content'] = '我的二级队员编号' . $lead['user_mynum'] . '开发了新商户，您将可获得' . $money3 . '元提成奖励';
                        $notice['n_type'] = 2;
                        $notice['n_user_id'] = $leaddata2['user_id'];
                        $notice['n_read'] = 0;//如果有已读未读，0是未读，1是已读
                        $notice['n_time'] = date('Y-m-d H:i:s');
                        Db::table('up_notice')->insert($notice);
                        //--------------------------------------
                    }
                }
            }
            Db::commit();
            allInNotice('注册送积分','新商户入驻赠送100积分',$shop['s_id']);
            allInJifen('新用户注册',1,100,$shop['s_id']);
            if($orderdata['o_which'] == 2){//商户
                sendJpush("{$orderdata['o_user_id']}",'你开发的商户:' . $shop['s_name'] . ',入驻申请审核成功',array('a'=>'b'),2,2,2);
            }else{//业务员
                sendJpush("{$orderdata['o_user_id']}",'你开发的商户:' . $shop['s_name'] . ',入驻申请审核成功',array('a'=>'b'),2,2,3);
            }
            return array('status'=>200,'msg'=>'ok');
        } catch (\Exception $e) {
            Db::rollback();
            return array('status'=>0,'msg'=>'状态更改失败');
        }
    }
    /**
     * 拒绝开发商户：后台调用
     * @return string
     */
    public function refuseShopIn($o_id,$reason,$adminname)
    {
        $where = array();
        $where['o_id'] = $o_id;
        $payinfo = Db::table('up_work_order')->where($where)
            ->field('o_user_pay money,o_number number,o_transaction_id transaction_id,o_agree,o_type,o_which')
            ->find();
        if ($payinfo['o_agree'] == 3) {
            return array('status' => 0, 'msg' => '已拒绝，请勿重复操作');
        }
        if ($payinfo['o_agree'] == 2) {
            return array('status' => 0, 'msg' => '已同意了');
        }
        Db::startTrans();
        try{
            if ($payinfo['o_type'] == 1) {
                $back = $this->refund($payinfo);
            } else {
                if($payinfo['o_which'] == 1){
                    $back = $this->refundWx($payinfo);
                }else{
                    $back = $this->refundWxShop($payinfo);
                }

            }

            if ($back['status'] != 200) {
                return array('status' => 0, 'msg' => $back['msg']);
            } else {
                $update = array();
                $update['o_admin'] = $adminname;
                $update['o_agree'] = 3;
                $update['o_reason'] = $reason;
                $update['o_agree_time'] = date('Y-m-d H:i:s');
                Db::table('up_work_order')->where($where)
                    ->update($update);
            }
            Db::commit();
            if ($back['status'] == 200) {
                //----------------入消息表---------------------
                $shop = Db::table('up_work_shops_copy')
                    ->where('s_ordernumber', $payinfo['number'])
                    ->find();
                $notice = array();
                $notice['n_title'] = '入驻申请审核失败';
                $notice['n_content'] = '你提交的' . $shop['s_name'] . '商户资料认证失败，认证费已退回，原因是：'.$reason.'，如需再次认证请重新提交。';
                $notice['n_type'] = 2;
                $notice['n_user_id'] = $shop['s_work_user_id'];
                $notice['n_read'] = 0;
                $notice['n_time'] = date('Y-m-d H:i:s');
                Db::table('up_notice')->insert($notice);
                if($payinfo['o_which'] == 2){//商户
                    sendJpush("{$shop['s_work_user_id']}",'你开发的商户:' . $shop['s_name'] . ',入驻申请审核失败',array('a'=>'b'),2,2,2);
                }else{//业务员
                    sendJpush("{$shop['s_work_user_id']}",'你开发的商户:' . $shop['s_name'] . ',入驻申请审核失败',array('a'=>'b'),2,2,3);
                }
                //--------------------------------------
            }
            return array('status'=>200,'msg'=>'操作成功');
        }catch (\Exception $e) {
            Db::rollback();
            return array('status'=>0,'msg'=>'操作失败');
        }
    }


    public function uuu()
    {
        $a = sendJpush("5b84d0686a99948de7bf57601d17ac90", '777', array('a' => 'b'), 2, 100, 2);
        dump($a);
        die;
    }
}
